#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：BookStore 
@File    ：forms.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/8/13/013 16:22 
"""

from django import forms

from index.models import Book, UserInfo
from django.forms import widgets


class TitleSearch(forms.Form):
    title = forms.CharField(label="书名", widget=forms.Textarea, required=True,
                            error_messages={"required": "请输入正确的title"})
    email = forms.EmailField(label="邮箱地址", error_messages={"required": "请输入正确的邮箱"})


class BookField(forms.Field):
    default_error_message = {
        'invalid': 'Enter a whole number',
        'not_exist': 'Book Not Exist',
    }

    def to_python(self, num):
        try:
            num = int(str(num).strip())
            return Book.objects.get(id=num)
        except (ValueError, TypeError):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        except Exception:
            raise ValidationError(self.error_messages['not_exist'], code='not_exist')


class AddstrField(forms.CharField):
    def clean(self, value):
        return "C语言中文网 %s " % super().clean(value)


# 自定义一个验证偶数的验证器，否则抛出异常
def even_validator(value):
    if value % 2 != 0:
        raise ValidationError('%d is not a even number' % value)


# 编写 EvenField字段，只可以接受偶数，否则抛出异常ValidationError
class EvenField(forms.IntegerField):
    # 使用构造函数__init__ 对其进行初始化，并添加验证器规则
    def __init__(self, **kwargs):
        super().__init__(validators=[even_validator], **kwargs)


class RegForm(forms.Form):
    name = forms.CharField(label="用户名")

    def clean_name(self):
        name = self.cleaned_data["name"]
        if len(name) < 6:
            raise forms.ValidationError("您注册的用户名字符太短了！")
        return name


class BookModelForm(forms.ModelForm):
    class Meta:
        model = Book
        labels = {"price": "零售价格"}
        exclude = ("retail_price",)


class UserModelForm(forms.ModelForm):
    class Meta:
        model = UserInfo
        fields = "__all__"
        widgets = {'password': widgets.PasswordInput()}
